using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using CodeIsBug.Common.Components.Configuration;
using CodeIsBug.Common.Model;
using Microsoft.IdentityModel.Tokens;

namespace CodeIsBug.Common.Helper;

public class JwtHelper()
{
    public (string accessToken, string refreshToken) GenerateJwtToken(TokenData tokenData)
    {
        var claims = new List<Claim>();
        claims.Add(new Claim("UserName", tokenData.UserName));
        claims.Add(new Claim("UserId", tokenData.UserId.ToString()));
        claims.Add(new Claim("UseAccount", tokenData.UserAccount));
        claims.Add(new Claim("UserPermission", tokenData.UserPermission.ToArray().ToJson()));
        claims.Add(new Claim("UserRolesId", tokenData.UserRolesId.ToArray().ToJson()));

        var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.JwtOptions.SecretKey));

        // 3. 选择加密算法
        var algorithm = SecurityAlgorithms.HmacSha256;

        // 4. 生成Credentials
        var signingCredentials = new SigningCredentials(secretKey, algorithm);

        // 5. 根据以上，生成token
        var jwtSecurityToken = new JwtSecurityToken(
            AppSettings.JwtOptions.Issuer, //Issuer
            AppSettings.JwtOptions.Audience, //Audience
            claims, //Claims,
            DateTime.Now, //notBefore
            DateTime.Now.AddSeconds(30), //expires
            signingCredentials //Credentials
        );
        var refClaims = new[]
        {
            new Claim("role", "refresh")
        };
        var refreshToken = new JwtSecurityToken(
            issuer: AppSettings.JwtOptions.Issuer, // 发布者
            audience: AppSettings.JwtOptions.Audience, // 接收者
            notBefore: DateTime.Now, // token签发时间
            expires: DateTime.Now.AddDays(7), // token过期时间
            claims: refClaims, // 该token内存储的自定义字段信息
            signingCredentials: new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256) // 用于签发token的秘钥算法
        );
        // 6. 将token变为string
        var accessToken = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
        var refreshTokenStr = new JwtSecurityTokenHandler().WriteToken(refreshToken);
        string berartoken = $"Bearer {accessToken}";
        return (berartoken, refreshTokenStr);
    }
}